<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>网站主页</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
    <link rel="stylesheet" href="/css/index.css">
    <script src="https://cdn.tiny.cloud/1/ultqulo896fvxj3l2o617lktjikveakzhi2e5rus5uzei7cw/tinymce/6/tinymce.min.js" referrerpolicy="origin"></script>
</head>
<body>
    <nav class="navbar">
        <a href="/" class="navbar-brand">
            <i class="fas fa-cube"></i>
            内容分享平台
        </a>
        <div class="nav-links">
            <div class="search-container">
                <input type="text" id="searchInput" placeholder="搜索标题...">
                <button class="search-btn" onclick="handleSearch()">
                    <i class="fas fa-search"></i>
                </button>
            </div>
            <a href="/login" class="login-btn" id="loginBtn">
                <i class="fas fa-sign-in-alt"></i> 登录
            </a>
            <div class="user-info" id="userInfo">
                <div class="user-avatar">
                    <i class="fas fa-user-circle"></i>
                </div>
                <div class="user-dropdown">
                    <span id="username"></span>
                    <div class="dropdown-content">
                        <a href="/admin" id="adminLink" style="display: none;">
                            <i class="fas fa-cog"></i> 管理后台
                        </a>
                        <a href="#" onclick="handleLogout(event)">
                            <i class="fas fa-sign-out-alt"></i> 退出登录
                        </a>
                    </div>
                </div>
            </div>
        </div>
    </nav>

    <div class="main-content">
        <!-- 添加发布按钮，只有登录用户可见 -->
        <div id="publishButton" style="display: none; margin-bottom: 20px;">
            <button class="btn-publish" onclick="showAddContentForm()">
                <i class="fas fa-plus"></i> 发布内容
            </button>
        </div>

        <!-- 修改添加内容表单部分 -->
        <div id="addContentForm" class="modal" style="display: none;">
            <div class="modal-content">
                <div class="modal-header">
                    <h4><i class="fas fa-plus-circle"></i> 发布新内容</h4>
                    <span class="close-btn" onclick="hideAddContentForm()">
                        <i class="fas fa-times"></i>
                    </span>
                </div>
                <form onsubmit="handleAddContent(event)">
                    <div class="form-group">
                        <label>标题：</label>
                        <input type="text" id="newTitle" required>
                    </div>
                    <div class="form-group">
                        <label>分类：</label>
                        <select id="newCategory">
                            <option value="news">新闻</option>
                            <option value="notice">公告</option>
                            <option value="article">文章</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label>内容：</label>
                        <textarea id="newContentEditor"></textarea>
                    </div>
                    <div class="form-buttons">
                        <button type="submit" class="btn-success">
                            <i class="fas fa-check"></i> 确认发布
                        </button>
                        <button type="button" class="btn-cancel" onclick="hideAddContentForm()">
                            <i class="fas fa-times"></i> 取消
                        </button>
                    </div>
                </form>
            </div>
        </div>

        <div class="content-grid" id="contentGrid">
            <!-- 内容将通过 JavaScript 动态加载 -->
        </div>
        <div class="loading" id="loading">
            <div class="loading-spinner"></div>
        </div>
    </div>

    <div class="toast-container" id="toastContainer"></div>

    <script>
        // Socket.IO 相关代码重构
        let socket = null;

        // 初始化Socket连接
        function initializeSocket(userId) {
            if (!socket) {
                socket = io();

                // Socket连接事件
                socket.on('connect', () => {
                    console.log('Socket connected:', socket.id);
                    if (userId) {
                        socket.emit('store_user_socket', userId);
                    }
                });

                // 强制登出事件
                socket.on('force_logout', (data) => {
                    console.log('Received force logout event:', data);
                    showToast(data.message, 'info');
                    handleLogout();
                });

                // 断开连接事件
                socket.on('disconnect', () => {
                    console.log('Socket disconnected');
                });
            }
            return socket;
        }

        // 修改检查登录状态函数
        async function checkLoginStatus() {
            try {
                const response = await fetch('/api/login/status');
                const data = await response.json();
                
                const loginBtn = document.getElementById('loginBtn');
                const userInfo = document.getElementById('userInfo');
                const username = document.getElementById('username');
                const publishButton = document.getElementById('publishButton');
                const adminLink = document.getElementById('adminLink');
                
                if (data.success) {
                    loginBtn.style.display = 'none';
                    userInfo.style.display = 'flex';
                    username.textContent = data.user.username;
                    publishButton.style.display = 'block';
                    
                    // 根据用户角色显示/隐藏管理后台链接
                    if (data.user.role === 'admin') {
                        adminLink.style.display = 'flex';
                    } else {
                        adminLink.style.display = 'none';
                    }
                    
                    // 初始化socket连接
                    const socket = initializeSocket(data.user.id);
                    if (socket && !socket.connected) {
                        socket.connect();
                    }
                } else {
                    loginBtn.style.display = 'flex';
                    userInfo.style.display = 'none';
                    username.textContent = '';
                    publishButton.style.display = 'none';
                    adminLink.style.display = 'none';
                    
                    // 如果未登录且socket存在，断开连接
                    if (socket && socket.connected) {
                        socket.disconnect();
                    }
                }
            } catch (error) {
                console.error('检查登录状态失败:', error);
            }
        }

        // 修改页面可见性变化处理
        document.addEventListener('visibilitychange', () => {
            if (!document.hidden) {
                checkLoginStatus(); // 重新检查登录状态，这会处理socket连接
            }
        });

        // 修改登出处理函数
        async function handleLogout(event) {
            if (event) {
                event.preventDefault();
            }
            
            try {
                const response = await fetch('/api/logout', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    }
                });

                const data = await response.json();
                
                if (data.success) {
                    // 清本地存储
                    localStorage.clear();
                    sessionStorage.clear();
                    
                    // 断开socket连接
                    if (socket && socket.connected) {
                        socket.disconnect();
                        socket = null; // 清除socket实例
                    }
                    
                    showToast('登出成功', 'success');
                    // 重定向到登录页
                    setTimeout(() => {
                        window.location.href = '/';
                    }, 1000);  // 1000毫秒 = 1秒

                } else {
                    showToast(data.message || '退出失败', 'error');
                }
            } catch (error) {
                console.error('退出失败:', error);
                showToast('退出失败: ' + error.message, 'error');
            }
        }

        // 页面关闭或刷新前的处理
        window.addEventListener('beforeunload', () => {
            if (socket && socket.connected) {
                socket.disconnect();
            }
        });

        // 加载内容列表
        async function loadContents(category = 'all') {
            const loading = document.getElementById('loading');
            const contentGrid = document.getElementById('contentGrid');
            
            loading.style.display = 'flex';
            try {
                const response = await fetch('/api/public/contents' + (category !== 'all' ? `?category=${category}` : ''));
                const data = await response.json();
                
                if (data.success) {
                    contentGrid.innerHTML = data.contents.map(content => `
                        <div class="content-card">
                            <div class="content-header">
                                <h3 class="content-title">${content.title}</h3>
                                <div class="content-meta">
                                    <span class="content-category">${getCategoryName(content.category)}</span>
                                    <span>${new Date(content.created_at).toLocaleDateString()}</span>
                                </div>
                            </div>
                            <div class="content-body">
                                ${content.content}
                            </div>
                            <div class="content-footer">
                                <span>作者: ${content.author}</span>
                                <span><i class="far fa-clock"></i> ${getTimeAgo(content.created_at)}</span>
                            </div>
                        </div>
                    `).join('');
                }
            } catch (error) {
                console.error('加载内容失败:', error);
            } finally {
                loading.style.display = 'none';
            }
        }

        function getCategoryName(category) {
            const categories = {
                news: '新闻',
                notice: '公告',
                article: '文章'
            };
            return categories[category] || category;
        }

        function getTimeAgo(date) {
            const seconds = Math.floor((new Date() - new Date(date)) / 1000);
            
            let interval = seconds / 31536000;
            if (interval > 1) return Math.floor(interval) + ' 年前';
            
            interval = seconds / 2592000;
            if (interval > 1) return Math.floor(interval) + ' 个月前';
            
            interval = seconds / 86400;
            if (interval > 1) return Math.floor(interval) + ' 天前';
            
            interval = seconds / 3600;
            if (interval > 1) return Math.floor(interval) + ' 小时前';
            
            interval = seconds / 60;
            if (interval > 1) return Math.floor(interval) + ' 分钟前';
            
            return Math.floor(seconds) + ' 秒前';
        }

        // 添加分类过滤功能
        document.querySelectorAll('.filter-btn').forEach(btn => {
            btn.addEventListener('click', (e) => {
                e.preventDefault();
                document.querySelectorAll('.filter-btn').forEach(b => b.classList.remove('active'));
                btn.classList.add('active');
                loadContents(btn.dataset.category);
            });
        });

        // 初始化编辑器
        function initEditor(selector) {
            tinymce.init({
                selector: selector,
                height: 500,
                plugins: [
                    'advlist', 'autolink', 'lists', 'link', 'image', 'charmap', 'preview',
                    'anchor', 'searchreplace', 'visualblocks', 'code', 'fullscreen',
                    'insertdatetime', 'media', 'table', 'help', 'wordcount'
                ],
                toolbar: 'undo redo | blocks | ' +
                    'bold italic forecolor | alignleft aligncenter ' +
                    'alignright alignjustify | bullist numlist outdent indent | ' +
                    'removeformat | image | help',
                language: 'zh_CN',
                images_upload_url: '/api/upload',
                images_upload_handler: async function (blobInfo, progress) {
                    try {
                        const formData = new FormData();
                        formData.append('image', blobInfo.blob(), blobInfo.filename());

                        const response = await fetch('/api/upload', {
                            method: 'POST',
                            body: formData
                        });

                        const data = await response.json();
                        if (data.success) {
                            return data.url;
                        }
                        throw new Error('上传失败');
                    } catch (error) {
                        console.error('图片上传失败:', error);
                        throw error;
                    }
                },
                file_picker_types: 'image',
                content_style: 'body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol"; font-size: 14px; }'
            });
        }

        // 修改显示添加内容表单函数
        function showAddContentForm() {
            const modal = document.getElementById('addContentForm');
            modal.style.display = 'flex';
            document.body.style.overflow = 'hidden';
            
            // 清空表单内容
            document.getElementById('newTitle').value = '';
            tinymce.get('newContentEditor').setContent('');
        }

        // 修改隐藏添加内容表函数
        function hideAddContentForm() {
            const modal = document.getElementById('addContentForm');
            modal.style.display = 'none';
            document.body.style.overflow = 'auto';
            
            // 清空表单内容
            document.getElementById('newTitle').value = '';
            tinymce.get('newContentEditor').setContent('');
        }

        // 修改发布内容处理函数
        async function handleAddContent(event) {
            event.preventDefault();
            
            try {
                const title = document.getElementById('newTitle').value;
                const category = document.getElementById('newCategory').value;
                const content = tinymce.get('newContentEditor').getContent();

                const response = await fetch('/api/contents', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({ 
                        title,
                        category,
                        content,
                        status: 'published' // 默认设置为已发布状态
                    })
                });

                const data = await response.json();
                
                if (data.success) {
                    showToast('内容发布成功', 'success');
                    hideAddContentForm();
                    loadContents();
                } else {
                    throw new Error(data.message || '发布失败');
                }
            } catch (error) {
                showToast(error.message || '发布内容失败', 'error');
                console.error('发布失败:', error);
            }
        }

        // 页面加载时初始化编辑器
        document.addEventListener('DOMContentLoaded', function() {
            initEditor('#newContentEditor');
            checkLoginStatus();
            loadContents();
        });

        // 修改登录按钮的链接处理
        document.addEventListener('DOMContentLoaded', function() {
            const loginBtn = document.getElementById('loginBtn');
            if (loginBtn) {
                loginBtn.addEventListener('click', function(e) {
                    e.preventDefault();
                    // 存储当前页面URL
                    sessionStorage.setItem('returnUrl', window.location.href);
                    window.location.href = '/login';
                });
            }
        });

        // 显示提示框的函数
        function showToast(message, type = 'info') {
            const container = document.getElementById('toastContainer');
            const toast = document.createElement('div');
            toast.className = `toast ${type}`;
            
            let icon = '';
            switch(type) {
                case 'success':
                    icon = 'check-circle';
                    break;
                case 'error':
                    icon = 'times-circle';
                    break;
                default:
                    icon = 'info-circle';
            }
            
            toast.innerHTML = `
                <i class="fas fa-${icon} toast-icon"></i>
                <div class="toast-message">${message}</div>
            `;
            
            container.appendChild(toast);
            
            // 3秒后移除提示框
            setTimeout(() => {
                toast.addEventListener('animationend', () => {
                    container.removeChild(toast);
                });
            }, 3000);
        }

        // 搜索功能
        async function handleSearch() {
            const searchTerm = document.getElementById('searchInput').value.trim();
            if (!searchTerm) {
                showToast('请输入搜索内容', 'info');
                return;
            }

            const loading = document.getElementById('loading');
            const contentGrid = document.getElementById('contentGrid');
            
            try {
                loading.style.display = 'flex';
                const response = await fetch(`/api/public/contents?search=${encodeURIComponent(searchTerm)}`);
                const data = await response.json();
                
                if (data.success) {
                    if (data.contents.length === 0) {
                        showToast(`未找到包含"${searchTerm}"的内容`, 'info');
                        contentGrid.innerHTML = '';
                    } else {
                        contentGrid.innerHTML = data.contents.map(content => `
                            <div class="content-card">
                                <div class="content-header">
                                    <h3 class="content-title">${content.title}</h3>
                                    <div class="content-meta">
                                        <span class="content-category">${getCategoryName(content.category)}</span>
                                        <span>${new Date(content.created_at).toLocaleDateString()}</span>
                                    </div>
                                </div>
                                <div class="content-body">
                                    ${content.content}
                                </div>
                                <div class="content-footer">
                                    <span>作者: ${content.author}</span>
                                    <span><i class="far fa-clock"></i> ${getTimeAgo(content.created_at)}</span>
                                </div>
                            </div>
                        `).join('');
                    }
                } else {
                    showToast('搜索失败', 'error');
                }
            } catch (error) {
                console.error('搜索失败:', error);
                showToast('搜索失败，请重试', 'error');
            } finally {
                loading.style.display = 'none';
            }
        }

        // 添加回车键搜索功能
        document.getElementById('searchInput').addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {
                handleSearch();
            }
        });
    </script>
</body>
</html> 